﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Joshi.Utils.Imap;
using System.Net;
using System.Xml;
using System.IO;

namespace ImapLibraryTestWinForms
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //https://mail01.korablik.local/owa/SP10_spfarm@KORABLIK.ru/

            string uid = "uid";
            string pwd = "pwd";
            string ADName = "KORABLIK";
            string DomainDNSName = @"mail01.korablik.local";

            MailUtil mUtil = new MailUtil(uid, pwd, ADName, DomainDNSName);
            List<Mail> inboxList = mUtil.GetUnreadMail();
        }

    }

    class MailUtil
    {

        #region Members

        private CredentialCache creds = new CredentialCache();
        private string _uid = "";
        public string uid
        { 
            get 
            {
                return _uid;
            }
        }
        private string _pwd = "";
        public string pwd
        {
            get
            {
                return _pwd;
            }
        }
        private string _domain = "";
        public string domain
        {
            get
            {
                return _domain;
            }
        }
        private string _DomainDNS_name = "";
        public string DomainDNS_name
        {
            get
            {
                return _DomainDNS_name;
            }
        }
        public string inboxUrlStr
        {
            get
            {
                // https://mail01.korablik.local/owa/SP10_spfarm@KORABLIK.ru/
                return @"https://mail01.korablik.local/owa/morozovsa@KORABLIK.ru/";
                //return @"http://" + DomainDNS_name + @"/Exchange/" + uid + "@KORABLIK.ru/Inbox/";
            }
        }

        #endregion

        public MailUtil(string parUid, string parPwd, string parAD_name, string parDomainDNS_name)
        {
            _uid = parUid;
            _pwd = parPwd;
            _domain = parAD_name;
            _DomainDNS_name = parDomainDNS_name;


            // set up webdav connection to exchange
            this.creds = new CredentialCache();
            this.creds.Add(
                new Uri(
                    inboxUrlStr)
                    , "Basic"
                    , new NetworkCredential(uid, pwd, parAD_name));
        }

        /// <summary>
        /// Gets all unread emails in a user's Inbox
        /// </summary>
        /// <returns>A list of unread mail messages</returns>
        public List<Mail> GetUnreadMail()
        {
            List<Mail> unreadMail = new List<Mail>();

string reqStr =
@"<?xml version=""1.0""?>
<g:searchrequest xmlns:g=""DAV:"">
    <g:sql>
        SELECT
            ""urn:schemas:mailheader:from"", ""urn:schemas:httpmail:textdescription""
        FROM
            " + inboxUrlStr + @" 
        WHERE 
            ""urn:schemas:httpmail:read"" = FALSE 
            AND ""urn:schemas:httpmail:subject"" = 'tbintg' 
            AND ""DAV:contentclass"" = 'urn:content-classes:message' 
        </g:sql>
</g:searchrequest>";

            byte[] reqBytes = Encoding.UTF8.GetBytes(reqStr);

            // set up web request
            HttpWebRequest request = 
                (HttpWebRequest)HttpWebRequest.Create(inboxUrlStr);
            request.Credentials = this.creds;
            request.Method = "SEARCH";
            request.ContentLength = reqBytes.Length;
            request.ContentType = "text/xml";
            request.Timeout = 300000;


            using (Stream requestStream = request.GetRequestStream())
            {
                try
                {
                    requestStream.Write(reqBytes, 0, reqBytes.Length);
                }
                catch
                {
                }
                finally
                {
                    requestStream.Close();
                }
            }

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            
            using (Stream responseStream = response.GetResponseStream())
            {
                try
                {

                    StringBuilder sb = new StringBuilder();
                    byte[] buf = new byte[1024];
                    int offset = 0;
                    int countbytesread = 1;
                    do
                    {
                        countbytesread = responseStream.Read(buf, offset, 1024);
                        if (countbytesread > 0)
                        {
                            offset += countbytesread;
                            for (int i = 0; i < countbytesread; i++)
                                sb.Append(buf[i]);
                        }
                    } while (countbytesread > 0);
                    string str = sb.ToString();


                    XmlDocument document = new XmlDocument();
                    document.Load(responseStream);

                    // set up namespaces
                    XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable);
                    nsmgr.AddNamespace("a", "DAV:");
                    nsmgr.AddNamespace("b", "urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/");
                    nsmgr.AddNamespace("c", "xml:");
                    nsmgr.AddNamespace("d", "urn:schemas:mailheader:");
                    nsmgr.AddNamespace("e", "urn:schemas:httpmail:");

                    // Load each response (each mail item) into an object
                    XmlNodeList responseNodes = document.GetElementsByTagName("a:response");
                    foreach (XmlNode responseNode in responseNodes)
                    {
                        // get the <propstat> node that contains valid HTTP responses
                        XmlNode uriNode = responseNode.SelectSingleNode("child::a:href", nsmgr);
                        XmlNode propstatNode = responseNode.SelectSingleNode("descendant::a:propstat[a:status='HTTP/1.1 200 OK']", nsmgr);
                        if (propstatNode != null)
                        {
                            // read properties of this response, and load into a data object
                            XmlNode fromNode = propstatNode.SelectSingleNode("descendant::d:from", nsmgr);
                            XmlNode descNode = propstatNode.SelectSingleNode("descendant::e:textdescription", nsmgr);

                            // make new data object
                            Mail mail = new Mail();
                            if (uriNode != null)
                                mail.Uri = uriNode.InnerText;
                            if (fromNode != null)
                                mail.From = fromNode.InnerText;
                            if (descNode != null)
                                mail.Body = descNode.InnerText;
                            unreadMail.Add(mail);
                        }
                    }

                }
                catch (System.Exception e)
                {
                    string msg = e.Message;
                }
                finally
                {
                    responseStream.Close();
                }
            }

            return unreadMail;
        }
    }

    class Mail
    {
        private string uri;
        private string from;
        private string body;

        public string Uri
        {
            get { return this.uri; }
            set { this.uri = value; }
        }

        public string From
        {
            get { return this.from; }
            set { this.from = value; }
        }

        public string Body
        {
            get { return this.body; }
            set { this.body = value; }
        }
    }

}
